using Admin.NET.Core;
using Admin.NET.Core.Util.LowCode.Front.Code;
using Admin.NET.Core.Util.LowCode.Front.Model;
using Furion;
using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.Extras.Admin.NET.Entity;
using Furion.Extras.Admin.NET.Util.LowCode.Front.Code;
using Furion.FriendlyException;
using Furion.ViewEngine;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Newtonsoft.Json;
using OfficeOpenXml;
using StackExchange.Profiling.Internal;
using System.Reflection;
using System.Text;
using System.Web;

namespace Admin.NET.Application.CodeGen
{
    /// <summary>
    /// 代码生成器服务
    /// </summary>
    [Route("api/[Controller]")]
    [ApiDescriptionSettings(Name = "CodeGenerate", Order = 100)]
    public class CodeGenerateService : ICodeGenService, IDynamicApiController, ITransient
    {
        private readonly IRepository<SysCodeGen> _sysCodeGenRep; // 代码生成器仓储
        private readonly IRepository<SysLowCode> _sysLowCodeRep; // 代码生成器仓储
        private readonly ICodeGenConfigService _codeGenConfigService;
        private readonly IViewEngine _viewEngine;
        private readonly ISysEnumDataService _sysEnumDataService;
        private readonly IRepository<SysMenu> _sysMenuRep; // 菜单表仓储

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sysCodeGenRep"></param>
        /// <param name="sysLowCodeRep"></param>
        /// <param name="codeGenConfigService"></param>
        /// <param name="viewEngine"></param>
        /// <param name="sysMenuRep"></param>
        /// <param name="sysEnumDataService"></param>
        public CodeGenerateService(IRepository<SysCodeGen> sysCodeGenRep,
                              IRepository<SysLowCode> sysLowCodeRep,
                              ICodeGenConfigService codeGenConfigService,
                              IViewEngine viewEngine,
                              IRepository<SysMenu> sysMenuRep,
            ISysEnumDataService sysEnumDataService)
        {
            _sysCodeGenRep = sysCodeGenRep;
            _sysLowCodeRep = sysLowCodeRep;
            _codeGenConfigService = codeGenConfigService;
            _viewEngine = viewEngine;
            _sysMenuRep = sysMenuRep;
            _sysEnumDataService = sysEnumDataService;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<SysCodeGen>> QueryCodeGenPageList([FromQuery] CodeGenPageInput input)
        {
            //if(input.)
            //// 加入配置表中
            //_codeGenConfigService.AddList(GetColumnList(input.Adapt<AddCodeGenInput>()), codeGen);

            var tableName = !string.IsNullOrEmpty(input.TableName?.Trim());
            var busName = !string.IsNullOrEmpty(input.BusName?.Trim());
            var codeGens = await _sysCodeGenRep.DetachedEntities
                                               .Where((tableName, u => EF.Functions.Like(u.TableName, $"%{input.TableName.Trim()}%")))
                                               .Where((busName, u => EF.Functions.Like(u.BusName, $"%{input.BusName.Trim()}%")))
                                               .ToADPagedListAsync(input.PageNo, input.PageSize);
            return codeGens;
        }

        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task AddCodeGen(AddCodeGenInput input)
        {
            var isExist = await _sysCodeGenRep.DetachedEntities.AnyAsync(u => u.TableName == input.TableName);
            if (isExist)
                throw Oops.Oh(ErrorCode.D1400);

            if (input.LowCodeId != null && input.LowCodeId > 0)
            {
                isExist = await _sysCodeGenRep.DetachedEntities.AnyAsync(u => u.LowCodeId == input.LowCodeId);
            }

            if (!isExist)
            {
                var codeGen = input.Adapt<SysCodeGen>();
                var newCodeGen = await codeGen.InsertNowAsync();

                // 加入配置表中
                await _codeGenConfigService.DelAndAddList(GetColumnList(input), newCodeGen.Entity);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="inputs"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public Task DeleteCodeGen(List<DeleteCodeGenInput> inputs)
        {
            if (inputs == null || inputs.Count < 1) return Task.Run(() => { });

            var taskList = new List<Task>();

            inputs.ForEach(u =>
            {
                taskList.Add(_sysCodeGenRep.DeleteAsync(u.Id));
                // 删除配置表中
                taskList.Add(_codeGenConfigService.Delete(u.Id));
            });
            return Task.WhenAll(taskList);//等待所有任务完成
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task UpdateCodeGen(UpdateCodeGenInput input)
        {
            var isExistObjOther = await _sysCodeGenRep.DetachedEntities.FirstOrDefaultAsync(u => u.TableName == input.TableName && u.Id != input.Id);
            if (isExistObjOther != null)
                throw Oops.Oh(ErrorCode.D1400);

            var isExistObj = await _sysCodeGenRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id);
            if (isExistObj == null)
                throw Oops.Oh(ErrorCode.D1002);

            //判断如果生成表变化了，就需要重置配置表 【Editby shaocx,2024-04-13】
            var isChangeTableName = false;
            if (input.TableName != isExistObj.TableName)
            {
                isChangeTableName = true;
            }

            var codeGen = input.Adapt<SysCodeGen>();
            await codeGen.UpdateAsync();


            if (isChangeTableName)
            {
                // 加入配置表中
                await _codeGenConfigService.DelAndAddList(GetColumnList(input.Adapt<AddCodeGenInput>()), codeGen);
            }
        }

        /// <summary>
        /// 刷新配置表
        /// </summary>
        /// <returns></returns>
        [HttpGet("refresh/{id}")]
        public void Refresh(long id)
        {
            var item = _sysCodeGenRep.Where(x => x.Id == id).FirstOrDefault();
            // 加入配置表中
            _codeGenConfigService.DelAndAddList(GetColumnList(item.Adapt<AddCodeGenInput>()), item);
        }

        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<SysCodeGen> GetCodeGen([FromQuery] QueryCodeGenInput input)
        {
            return await _sysCodeGenRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id);
        }

        /// <summary>
        /// 获取数据库库集合
        /// </summary>
        /// <returns></returns>
        [HttpGet("DatabaseList")]
        public List<DatabaseOutput> GetDatabaseList()
        {
            var DbContextLocators = AppDomain.CurrentDomain.GetAssemblies()
                        .SelectMany(
                            a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IDbContextLocator)))
                        )
                        .Select(x => new DatabaseOutput { DatabaseName = x.Name, DatabaseComment = x.FullName })
                        .ToList();

            return DbContextLocators;
        }

        /// <summary>
        /// 获取数据库表(实体)集合
        /// </summary>
        /// <returns></returns>
        [HttpGet("InformationList")]
        public List<TableOutput> GetTableList(string dbContextLocatorName)
        {
            var dbContext = Db.GetDbContext();//默认数据库
            if (!string.IsNullOrEmpty(dbContextLocatorName))
            {
                var dbContentLocator = AppDomain.CurrentDomain.GetAssemblies()
                           .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IDbContextLocator)))).Where(x => x.Name == dbContextLocatorName).FirstOrDefault();

                dbContext = Db.GetDbContext(dbContentLocator);
            }
            // 获取实体类型属性
            //var entityType = dbContext.Model.GetEntityTypes()要改成 var entityType = dbContext.GetService<IDesignTimeModel>().Model.GetEntityTypes()

            return dbContext.GetService<IDesignTimeModel>().Model.GetEntityTypes().Select(u => new TableOutput
            {
                DatabaseName = dbContextLocatorName,
                TableName = u.GetDefaultTableName(),
                TableComment = u.GetComment()
            }).ToList();
        }

        /// <summary>
        /// 根据表名获取列
        /// </summary>
        /// <returns></returns>
        [HttpGet("ColumnList/{databaseName}/{tableName}")]
        public List<TableColumnOuput> GetColumnListByTableName(string databaseName, string tableName)
        {
            var dbContext = Db.GetDbContext();//默认数据库
            if (!string.IsNullOrEmpty(databaseName))
            {
                var dbContentLocator = AppDomain.CurrentDomain.GetAssemblies()
                           .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IDbContextLocator)))).Where(x => x.Name == databaseName).FirstOrDefault();

                dbContext = Db.GetDbContext(dbContentLocator);
            }
            // 获取实体类型属性
            var entityType = dbContext.GetService<IDesignTimeModel>().Model.GetEntityTypes().FirstOrDefault(u => u.ClrType.Name == tableName);
            if (entityType == null) return null;

            // 获取原始类型属性
            var type = entityType.ClrType;
            if (type == null) return null;

            // 按原始类型的顺序获取所有实体类型属性（不包含导航属性，会返回null）
            return type.GetProperties().Select(propertyInfo => entityType.FindProperty(propertyInfo.Name))
                       .Where(p => p != null).Select(p => new TableColumnOuput
                       {
                           ColumnName = p.Name,
                           ColumnKey = p.IsKey().ToString(),
                           DataType = p.PropertyInfo.PropertyType.ToString(),
                           NetType = CodeGenUtil.ConvertDataType(p.PropertyInfo.PropertyType.ToString()),
                           ColumnComment = p.GetComment()
                       }).ToList();
        }

        /// <summary>
        /// 获取数据表列（实体属性）集合
        /// </summary>
        /// <returns></returns>
        [NonAction]
        public List<TableColumnOuput> GetColumnList([FromQuery] AddCodeGenInput input)
        {
            var dbContext = Db.GetDbContext();//默认数据库
            if (!string.IsNullOrEmpty(input.DatabaseName))
            {
                var dbContentLocator = AppDomain.CurrentDomain.GetAssemblies()
                           .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IDbContextLocator)))).Where(x => x.Name == input.DatabaseName).FirstOrDefault();

                dbContext = Db.GetDbContext(dbContentLocator);
            }
            // 获取实体类型属性
            var entityType = dbContext.GetService<IDesignTimeModel>().Model.GetEntityTypes()
                .FirstOrDefault(u => u.ClrType.Name == input.TableName);
            if (entityType == null) return null;

            // 获取原始类型属性
            var type = entityType.ClrType;
            if (type == null) return null;

            // 按原始类型的顺序获取所有实体类型属性（不包含导航属性，会返回null）
            return type.GetProperties().Select(propertyInfo => entityType.FindProperty(propertyInfo.Name))
                       .Where(p => p != null)
                       .Select(p => new TableColumnOuput
                       {
                           ColumnName = p.Name,
                           IsNullable = p.IsNullable,
                           ColumnKey = p.IsKey().ToString(),
                           DataType = p.PropertyInfo.PropertyType.ToString(),
                           ColumnComment = p.GetComment()
                       }).ToList();
        }

        /// <summary>
        /// 代码生成_本地项目
        /// </summary>
        /// <returns></returns>
        [HttpPost("runLocal")]
        public async Task<dynamic> RunLocal(SysCodeGen input)
        {
            return await CommonRun(input, "200");
        }

        /// <summary>
        /// 代码生成_压缩包方式下载
        /// </summary>
        /// <returns></returns>
        [HttpGet("runDown")]
        public async Task<IActionResult> RunDown(long id)
        {
            SysCodeGen input = await _sysCodeGenRep.Where(x => x.Id == id).FirstOrDefaultAsync();
            var ret = await CommonRun(input, "100");
            var _path = App.WebHostEnvironment.WebRootPath + @"\" + ret.url;

            var fileName = HttpUtility.UrlEncode($"代码生成({ret.fileName}).zip", Encoding.GetEncoding("UTF-8"));

            var path = Path.Combine(_path, "");
            return new FileStreamResult(new FileStream(path, FileMode.Open), "application/octet-stream") { FileDownloadName = fileName };
        }


        /// <summary>
        /// 代码生成
        /// </summary>
        /// <param name="input"></param>
        /// <param name="curGenerateType">200:生成本地，100：生成本地压缩包</param>
        /// <returns></returns>
        private async Task<dynamic> CommonRun(SysCodeGen input, string curGenerateType)
        {



            var templatePathList = GetTemplatePathList();
            var targetPathList = new List<string>();
            var zipPath = System.IO.Path.Combine(App.WebHostEnvironment.WebRootPath, "CodeGen", input.TableName);
            if (curGenerateType.StartsWith('1'))
            {
                targetPathList = GetZipPathList(input);
                if (Directory.Exists(zipPath))
                    Directory.Delete(zipPath, true);
            }
            else
                targetPathList = GetTargetPathList(input);

            var tableFieldList = await _codeGenConfigService.List(new CodeGenConfig() { CodeGenId = input.Id }); // 字段集合
            if (curGenerateType.StartsWith('2'))
            {
                CodeGenHelper.ValidateCodeGenConfig(tableFieldList);
            }
            for (var i = 0; i < templatePathList.Count; i++)
            {
                var tContent = System.IO.File.ReadAllText(templatePathList[i]);

                tableFieldList.ForEach(u =>
                {
                    u.NetTypeIsNullLableForQueryInput = "?";
                    u.NetTypeIsNullLableForAddEditOutParam = "";
                    switch (u.NetType.ToLower())
                    {
                        case "int":
                        case "int32":
                        case "long":
                        case "guid":
                        case "decimal":
                        case "datetime":
                        case "datetimeoffset":
                        case "bool": //增加布尔类型的条件 【Editby shaocx,2024-04-07】
                            u.NetTypeIsNullLable = "?";
                            if (u.WhetherRequired != "Y")
                            {
                                u.NetTypeIsNullLableForAddEditOutParam = "?";
                            }
                            break;
                        case "string":
                            u.NetTypeIsNullLableForQueryInput = "";
                            break;
                        default://其他，比如枚举 【Editby shaocx,2024-04-07】
                            if (u.WhetherRequired != "Y")
                            {
                                u.NetTypeIsNullLableForAddEditOutParam = "?";
                            }
                            break;
                    }
                    u.OriginalColumnName = u.ColumnName;
                });

                if (i >= 6) // 适应前端首字母小写
                {
                    tableFieldList.ForEach(u =>
                    {
                        u.ColumnName = u.ColumnName.Substring(0, 1).ToLower() + u.ColumnName[1..];
                    });
                }

                var queryWhetherList = tableFieldList.Where(u => u.QueryWhether == YesOrNot.Y.ToString()).ToList(); // 前端查询集合

                string FormDesign = "";

                if (input.LowCodeId != null && input.LowCodeId > 0)
                {
                    FormDesign = _sysLowCodeRep.Where(x => x.Id == input.LowCodeId).Select(x => x.FormDesign).FirstOrDefault();
                }

                List<Front_Dynamic> dynamicLoad_dict = new List<Front_Dynamic>();
                Dictionary<string, List<string>> dynamicData = new Dictionary<string, List<string>>();

                if (!string.IsNullOrEmpty(FormDesign))
                {
                    try
                    {
                        var AllDynamic = FormDesign.ConvertToFront().AllFront().AllDynamic();

                        AllDynamic.Where(x => x.Dynamic).Select(x => x.DynamicKey).ToList().ForEach(item =>
                        {
                            dynamicData.Add(item, new List<string>());
                            var d = item.GetDynamic();
                            if (d != null)
                            {
                                if (d.Head == "dict")
                                {
                                    dynamicLoad_dict.Add(d);
                                }
                            }
                        });
                    }
                    catch { }
                }

                try
                {
                    //获取导入功能自定义模板代码
                    StringBuilder templateContent = null;
                    //Service控制器生成导入功能自定义代码   updare by liuwq
                    if (templatePathList[i].IndexOf("Service.cs.vm") >= 0)
                    {
                        templateContent = CreateImportExcelTemplteCode(input, tableFieldList);
                    }
                    var tResult = _viewEngine.RunCompileFromCached(tContent, new
                    {

                        input.AuthorName,
                        input.BusName,
                        input.NameSpace,
                        input.ModuleName,//增加模块地址 【Editby shaocx,2024-04-07】
                        input.ProName,
                        input.DatabaseName,
                        input.IsOnlyQuery,
                        input.IsWhetherImport,
                        ClassName = input.TableName,
                        CamelizeClassName = input.TableName.Substring(0, 1).ToLower() + input.TableName[1..], //首字母小写
                        QueryWhetherList = queryWhetherList,
                        TableField = tableFieldList,
                        input.LowCodeId,
                        FormDesign,
                        DynamicData = JsonConvert.SerializeObject(dynamicData),
                        DynamicLoad_Dict = dynamicLoad_dict,
                        IsFile = tableFieldList.Where(x => x.DtoNetType.Contains("Front_FileDto")).Any(),
                        FileTableField = tableFieldList.Where(x => x.DtoNetType.Contains("Front_FileDto")).ToList(),

                        ImportExcelCustomizationContent = templateContent?.ToString()//导入功能自定义模板代码
                    }); ;

                    var dirPath = new DirectoryInfo(targetPathList[i]).Parent.FullName;
                    if (!Directory.Exists(dirPath))
                        Directory.CreateDirectory(dirPath);
                    System.IO.File.WriteAllText(targetPathList[i], tResult, Encoding.UTF8);
                }
                catch (Exception ex)
                {
                    throw Oops.Oh($"错误模板：{templatePathList[i]}。错误信息：{ex.Message}。");
                }






            }

            await AddMenu(input, input.DatabaseName.Substring(0, 5), input.TableName, input.BusName, input.MenuApplication, input.MenuPid, input.ModuleName);

            if (input.IsWhetherImport == true)
            {
                //创建导入模版
                await CreateImportTemplte(input);
            }



            // 非ZIP压缩返回空
            if (!curGenerateType.StartsWith('1'))
                return null;
            else
            {
                string downloadPath = zipPath + ".zip";
                // 判断是否存在同名称文件
                if (System.IO.File.Exists(downloadPath))
                    System.IO.File.Delete(downloadPath);
                System.IO.Compression.ZipFile.CreateFromDirectory(zipPath, downloadPath);
                //return new { url = $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Host.Value}/CodeGen/{input.TableName}.zip" };
                return new { url = $@"CodeGen\{input.TableName}.zip", fileName = input.TableName };
            }
        }

        //update by liuwq 20240418
        /// <summary>
        /// 创建导入功能自定义模板代码 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="tableFieldList"></param>
        /// <returns></returns>
        private static StringBuilder CreateImportExcelTemplteCode(SysCodeGen input, List<CodeGenConfig> tableFieldList)
        {
            StringBuilder templateContent = new StringBuilder();
            var whetherAddUpdate = tableFieldList.Where(u => u.WhetherAddUpdate == YesOrNot.Y.ToString()).ToList(); // 前端查询增改集合
            templateContent.AppendLine("                          ");
            templateContent.AppendLine($"                           var addItem = new {input.TableName}()");
            templateContent.AppendLine("                            {");
            templateContent.AppendLine("                               CreatedTime = SysHelper.GetNowTime(),");
            templateContent.AppendLine("                               CreatedUserId = SysHelper.GetUserId(),");
            templateContent.AppendLine("                               CreatedUserName = SysHelper.GetUserName(),");
            templateContent.AppendLine("                               UpdatedTime = SysHelper.GetNowTime(),");
            templateContent.AppendLine("                               UpdatedUserId = SysHelper.GetUserId(),");
            templateContent.AppendLine("                               UpdatedUserName = SysHelper.GetUserName()");
            templateContent.AppendLine("                             };");


            templateContent.AppendLine("                          #region 定义变量");
            foreach (var item in whetherAddUpdate)
            {
                templateContent.AppendLine($"                           var _{item.ColumnName} = \"\";//{item.ColumnComment}");
            }

            templateContent.AppendLine("                          #endregion");
            templateContent.AppendLine("                          ");

            templateContent.AppendLine("                          ");
            templateContent.AppendLine("                          #region 取值");
            foreach (var item in whetherAddUpdate)
            {
                templateContent.AppendLine($"                           _{item.ColumnName} = row[\"{item.ColumnComment}\"]?.ToString() ;");
            }

            templateContent.AppendLine("                          #endregion");
            templateContent.AppendLine("                          ");

            templateContent.AppendLine("                          ");
            templateContent.AppendLine("                          #region 验证");

            //数值类型验证
            List<string> numericalTypeList = new List<string>()
            {
                "int",
                "long",
                "decimal"
            };



            foreach (var item in whetherAddUpdate)
            {


                //必填字段验证是否为空
                if (item.WhetherRequired.Equals("Y"))
                {
                    templateContent.AppendLine("                          ");
                    templateContent.AppendLine($"                          if (string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                          {");
                    templateContent.AppendLine($"                            throw Oops.Oh($\"第{{index}}行[{item.ColumnComment}]{{_{item.ColumnName}}}不能为空！\");");
                    templateContent.AppendLine("                          }");
                    templateContent.AppendLine("                          ");


                }




                //验证值是否有效

                //验证bool值
                if (item.DtoNetType.Equals("bool"))
                {
                    templateContent.AppendLine($"                          if(!string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                          {");
                    templateContent.AppendLine($"                            if(!_{item.ColumnName}.Equals(\"是\") && !_{item.ColumnName}.Equals(\"否\"))");
                    templateContent.AppendLine("                             {");
                    templateContent.AppendLine($"                               throw Oops.Oh($\"第{{index}}行[{item.ColumnComment}]{{_{item.ColumnName}}}值不正确！\");");
                    templateContent.AppendLine("                             }");
                    templateContent.AppendLine("                             else");
                    templateContent.AppendLine("                             {");
                    templateContent.AppendLine($"                               bool out{item.ColumnName} = _{item.ColumnName}.Equals(\"是\") ? true : false;");
                    templateContent.AppendLine($"                               addItem.{item.ColumnName} = out{item.ColumnName};");
                    templateContent.AppendLine("                             }");
                    templateContent.AppendLine("                             }");
                    templateContent.AppendLine("                          ");

                }
                //验证枚举值是否有效
                else if (!string.IsNullOrWhiteSpace(item.DictTypeCode))//字典code不为空 是使用枚举值
                {
                    templateContent.AppendLine($"                          if(!string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                          {");
                    templateContent.AppendLine($"                          {item.DataType}  enum{item.ColumnName} = default({item.DataType});");
                    templateContent.AppendLine("                          ");
                    templateContent.AppendLine($"                             if(!Enum.TryParse<{item.DataType}>(_{item.ColumnName}, out enum{item.ColumnName})&&!string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                              {");
                    templateContent.AppendLine($"                                throw Oops.Oh($\"第{{index}}行[{item.ColumnComment}]{{_{item.ColumnName}}}值不正确！\");");
                    templateContent.AppendLine("                              }");
                    templateContent.AppendLine("                              else");
                    templateContent.AppendLine("                              {");
                    templateContent.AppendLine($"                                 addItem.{item.ColumnName} = enum{item.ColumnName};");
                    templateContent.AppendLine("                              }");
                    templateContent.AppendLine("                          ");
                    templateContent.AppendLine("                           }");

                }//验证数值是否有效
                else if (numericalTypeList.Any(a => a == item.DtoNetType))
                {


                    templateContent.AppendLine($"                          if(!string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                          {");
                    templateContent.AppendLine($"                              if (!{item.DtoNetType}.TryParse(_{item.ColumnName}, out {item.DtoNetType} out{item.ColumnName})&&!string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                              {");
                    templateContent.AppendLine($"                                 throw Oops.Oh($\"第{{index}}行[{item.ColumnComment}]{{_{item.ColumnName}}}值不正确！\");");
                    templateContent.AppendLine("                              }");
                    templateContent.AppendLine($"                              if (out{item.ColumnName} <= 0&&!string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                              {");
                    templateContent.AppendLine($"                                 throw Oops.Oh($\"第{{index}}行[{item.ColumnComment}]{{_{item.ColumnName}}}值不能小于等于0！\");");
                    templateContent.AppendLine("                              }");
                    templateContent.AppendLine("                              else");
                    templateContent.AppendLine("                              {");
                    templateContent.AppendLine($"                                 addItem.{item.ColumnName} = out{item.ColumnName};");
                    templateContent.AppendLine("                              }");
                    templateContent.AppendLine("                          ");
                    templateContent.AppendLine("                          }");

                }
                else
                {
                    templateContent.AppendLine($"                          if(!string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                          {");

                    //日期控件
                    if (item.EffectType == "datepicker")
                    {
                        templateContent.AppendLine($"                                addItem.{item.ColumnName} = Convert.ToDateTime(Convert.ToDateTime(_{item.ColumnName}).ToShortDateString());");
                    }//日期时间控件
                    else if (item.EffectType == "datetimepicker")
                    {
                        templateContent.AppendLine($"                                addItem.{item.ColumnName} =   Convert.ToDateTime(_{item.ColumnName});");
                    }
                    else
                    {
                        templateContent.AppendLine($"                                addItem.{item.ColumnName} = ({item.DtoNetType})_{item.ColumnName};");
                    }
                    templateContent.AppendLine("                           }");
                }







            }

            templateContent.AppendLine("                          #endregion");
            templateContent.AppendLine("                          ");



            return templateContent;
        }

        private async Task AddMenu(SysCodeGen input, string menucodePre, string className, string busName, string application, long pid, string _ModuleName)
        {
            // 定义菜单编码前缀
            var codePrefix = menucodePre + "_" + className.ToLower();//改为取数据库定位器的前五个字母方便区分业务 //"dilon_" + className.ToLower();

            // 先删除该表已生成的菜单列表
            var menus = await _sysMenuRep.DetachedEntities.Where(u => u.Code == codePrefix || u.Code.StartsWith(codePrefix + "_")).ToListAsync();
            await _sysMenuRep.DeleteAsync(menus);

            // 如果 pid 为 0 说明为顶级菜单, 需要创建顶级目录
            if (pid == 0)
            {
                //解决 选择父级菜单“顶级”会多生成一级菜单的问题 【Editby shaocx,2024-04-13】
                /*
                // 目录
                var menuType0 = new SysMenu
                {
                    Pid = 0,
                    Pids = "[0],",
                    Name = busName + "管理",
                    Code = codePrefix,
                    Type = MenuType.DIR,
                    Icon = "robot",
                    Router = "/" + className.ToLower(),
                    Component = "PageView",
                    Application = application
                };
                pid = _sysMenuRep.InsertNowAsync(menuType0).GetAwaiter().GetResult().Entity.Id;
                //*/
            }
            // 由于后续菜单会有修改, 需要判断下 pid 是否存在, 不存在报错
            else if (!await _sysMenuRep.DetachedEntities.AnyAsync(e => e.Id == pid))
                throw Oops.Oh(ErrorCode.D1505);

            // 菜单
            string _pids = "";
            if (pid == 0)
            {
                _pids = "[0],";
            }
            else
            {
                _pids = "[0],[" + pid + "],";
            }
            var menuType1 = new SysMenu
            {
                Pid = pid,
                Pids = _pids,
                Name = busName,
                Code = codePrefix + "_mgr",
                Type = MenuType.MENU,
                Router = "/" + className.ToLower(),
                Component = "main/" + _ModuleName + "/" + className + "/index",//增加 模块地址的配置【Editby shaocx,2024-04-07】
                Application = application,
                OpenType = MenuOpenType.COMPONENT
            };
            var pid1 = _sysMenuRep.InsertNowAsync(menuType1).GetAwaiter().GetResult().Entity.Id;

            // 按钮-page
            var menuType2 = new SysMenu
            {
                Pid = pid1,
                Pids = "[0],[" + pid + "],[" + pid1 + "],",
                Name = busName + "查询",
                Code = codePrefix + "_mgr_page",
                Type = MenuType.BTN,
                Permission = className + ":page",
                Application = application,
            }.InsertAsync();

            // 按钮-detail
            var menuType2_1 = new SysMenu
            {
                Pid = pid1,
                Pids = "[0],[" + pid + "],[" + pid1 + "],",
                Name = busName + "详情",
                Code = codePrefix + "_mgr_detail",
                Type = MenuType.BTN,
                Permission = className + ":detail",
                Application = application,
            }.InsertAsync();

            if (input.IsOnlyQuery != true)
            {
                // 按钮-add
                var menuType2_2 = new SysMenu
                {
                    Pid = pid1,
                    Pids = "[0],[" + pid + "],[" + pid1 + "],",
                    Name = busName + "增加",
                    Code = codePrefix + "_mgr_add",
                    Type = MenuType.BTN,
                    Permission = className + ":add",
                    Application = application,
                }.InsertAsync();

                // 按钮-delete
                var menuType2_3 = new SysMenu
                {
                    Pid = pid1,
                    Pids = "[0],[" + pid + "],[" + pid1 + "],",
                    Name = busName + "删除",
                    Code = codePrefix + "_mgr_delete",
                    Type = MenuType.BTN,
                    Permission = className + ":delete",
                    Application = application,
                }.InsertAsync();

                // 按钮-edit
                var menuType2_4 = new SysMenu
                {
                    Pid = pid1,
                    Pids = "[0],[" + pid + "],[" + pid1 + "],",
                    Name = busName + "编辑",
                    Code = codePrefix + "_mgr_edit",
                    Type = MenuType.BTN,
                    Permission = className + ":edit",
                    Application = application,
                }.InsertAsync();

                //按钮-导入
                if (input.IsWhetherImport == true)
                {
                    var menuType2_6 = new SysMenu
                    {
                        Pid = pid1,
                        Pids = "[0],[" + pid + "],[" + pid1 + "],",
                        Name = busName + "导入excel",
                        Code = codePrefix + "_mgr_import_excel",
                        Type = MenuType.BTN,
                        Permission = className + ":importExcel",
                        Application = application,
                    }.InsertAsync();
                }

            }


            var menuType2_5 = new SysMenu
            {
                Pid = pid1,
                Pids = "[0],[" + pid + "],[" + pid1 + "],",
                Name = busName + "导出excel",
                Code = codePrefix + "_mgr_export_excel",
                Type = MenuType.BTN,
                Permission = className + ":exportExcel",
                Application = application,
            }.InsertAsync();


        }

        /// <summary>
        /// 获取模板文件路径集合
        /// </summary>
        /// <returns></returns>
        private List<string> GetTemplatePathList()
        {
            var templatePath = App.WebHostEnvironment.WebRootPath + @"\Template\";
            return new List<string>()
            {
                templatePath + "Service.cs.vm",
                templatePath + "IService.cs.vm",
                templatePath + "Input.cs.vm",
                templatePath + "Output.cs.vm",
                //不再生成Dto文件 【Editby shaocx,2024-04-20】
                //templatePath + "Dto.cs.vm",
                templatePath + "Mapper.cs.vm",
                templatePath + "index.vue.vm",
                templatePath + "addForm.vue.vm",
                templatePath + "editForm.vue.vm",
                templatePath + "excelForm.vue.vm",
                templatePath + "Manage.js.vm",
            };
        }

        /// <summary>
        /// 设置生成文件路径
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private List<string> GetTargetPathList(SysCodeGen input)
        {
            //增加 模块路径的写入 【Editby shaocx,2024-04-07】
            var backendPath = new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.FullName + @"\" + input.NameSpace + @"\Service\" + input.ModuleName + @"\" + input.TableName + @"\";//后端文件夹父路径
            var servicePath = backendPath + input.TableName + "Service.cs";
            var iservicePath = backendPath + "I" + input.TableName + "Service.cs";
            var inputPath = backendPath + @"Dto\" + input.TableName + "Input.cs";
            var outputPath = backendPath + @"Dto\" + input.TableName + "Output.cs";
            //不再生成Dto文件 【Editby shaocx,2024-04-20】
            //var viewPath = backendPath + @"Dto\" + input.TableName + "Dto.cs";
            var mapperPath = backendPath + @"Map\" + input.TableName + "Mapper.cs";
            //增加 模块路径的写入 【Editby shaocx,2024-04-07】
            var frontendPath = new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.Parent.FullName + @"\" + input.FrontProName + @"\src\views\main\" + input.ModuleName + @"\";//前端文件夹父路径
            var indexPath = frontendPath + input.TableName + @"\index.vue";
            var addFormPath = frontendPath + input.TableName + @"\addForm.vue";
            var editFormPath = frontendPath + input.TableName + @"\editForm.vue";
            var excelFormPath = frontendPath + input.TableName + @"\excelForm.vue";
            //增加 模块路径的写入 【Editby shaocx,2024-04-07】
            var apiJsPath = new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.Parent.FullName + @"\" + input.FrontProName + @"\src\api\modular\main\" + input.ModuleName + @"\" + input.TableName + "Manage.js";

            return new List<string>()
            {
                servicePath,
                iservicePath,
                inputPath,
                outputPath,
                //不再生成Dto文件 【Editby shaocx,2024-04-20】
                //viewPath,
                mapperPath,
                indexPath,
                addFormPath,
                editFormPath,
                excelFormPath,
                apiJsPath
            };
        }

        /// <summary>
        /// 字符串首字母小写
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string LowercaseFirst(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input; // 如果输入为空，则直接返回
            }

            char firstChar = char.ToLower(input[0]); // 将第一个字符转换为小写
            string remainder = input.Length > 1 ? input.Substring(1) : ""; // 获取剩余的字符串部分
            return firstChar + remainder; // 返回首字母小写的字符串
        }


        /// <summary>
        /// 设置生成文件路径
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private List<string> GetZipPathList(SysCodeGen input)
        {
            var zipPath = System.IO.Path.Combine(App.WebHostEnvironment.WebRootPath, "CodeGen", input.TableName);

            var backendPath = System.IO.Path.Combine(zipPath, input.NameSpace, "Service", input.ModuleName, input.TableName);//后端文件夹父路径
            var servicePath = System.IO.Path.Combine(backendPath, input.TableName + "Service.cs");
            var iservicePath = System.IO.Path.Combine(backendPath, "I" + input.TableName + "Service.cs");
            var inputPath = System.IO.Path.Combine(backendPath, "Dto", input.TableName + "Input.cs");
            var outputPath = System.IO.Path.Combine(backendPath, "Dto", input.TableName + "Output.cs");
            var viewPath = System.IO.Path.Combine(backendPath, "Dto", input.TableName + "Dto.cs");
            var mapperPath = System.IO.Path.Combine(backendPath, "Dto", input.TableName + "Mapper.cs");


            var frontendPath = System.IO.Path.Combine(zipPath, input.FrontProName, "src", "views", "main", input.ModuleName, input.TableName);//前端文件夹父路径
            var indexPath = frontendPath + @"\index.vue";
            var addFormPath = frontendPath + @"\addForm.vue";
            var editFormPath = frontendPath + @"\editForm.vue";
            var excelFormPath = frontendPath + @"\excelForm.vue";
            //增加 模块路径的写入 【Editby shaocx,2024-04-07】
            var _apiJsPath = System.IO.Path.Combine(zipPath, input.FrontProName, "src", "api", "modular", "main", input.ModuleName);//前端文件夹父路径
            var apiJsPath = new DirectoryInfo(_apiJsPath) + @"\" + input.TableName + "Manage.js";

            return new List<string>()
            {
                servicePath,
                iservicePath,
                inputPath,
                outputPath,
                viewPath,
                mapperPath,
                indexPath,
                addFormPath,
                editFormPath,
                excelFormPath,
                apiJsPath
            };
        }


        /// <summary>
        /// 根据表名创建导入模版
        /// </summary>
        /// <param name="input"></param>
        private async Task CreateImportTemplte(SysCodeGen input)
        {
            string errMsg = string.Empty;
            //表名
            string tableName = input.TableName;
            var copayPath = TemplateConst.EXCEL_TEMPLATEFILE_导入模版路径 + "\\CommonTemplate.xlsx";
            string newPath = TemplateConst.EXCEL_TEMPLATEFILE_导入模版路径 + $"\\{tableName}{TemplateConst.EXCEL_TEMPLATEFILE_导入模版名称后缀}.xlsx";
            var tableFieldList = await _codeGenConfigService.List(new CodeGenConfig() { CodeGenId = input.Id }); // 字段集合
            CreatExcel(tableFieldList, copayPath, newPath);
        }


        /// <summary>
        /// 根据实体类名 生成导入excel模版
        /// </summary>
        /// <param name="tableFieldList">代码生成选择配置表的字段</param>
        /// <param name="copayPath"></param>
        /// <param name="newPath"></param>
        private void CreatExcel(List<CodeGenConfig> tableFieldList, string copayPath, string newPath)
        {
            string errMsg = string.Empty;
            try
            {
                #region 验证原始导入模板文件是否存在
                if (!File.Exists(copayPath))
                {
                    errMsg = $"用来复制生成模版的EXCEL文件不存在";
                    throw Oops.Oh($"生成导入模版文件异常：{errMsg}");
                }
                #endregion

                //获取模板文件
                FileInfo copyFile = new FileInfo(copayPath);

                // 检查新生成的导入模版文件是否存在，存在就删除，以避免可能的异常。
                if (File.Exists(newPath))
                {
                    File.Delete(newPath); // 删除文件
                }
                //复制原始导入模版，创建新的导入模版文件
                copyFile.CopyTo(newPath, true);
                FileInfo existingFile = new FileInfo(newPath);
                using (ExcelPackage package = new ExcelPackage(existingFile))
                {
                    //获取模板内容
                    ExcelWorksheet worksheet = package.Workbook.Worksheets[0];//获取第一个worksheet
                    //行和列都是从1开始，而不是从0开始！！！
                    int _remarkRowIndex = 1;//worksheet 行索引（说明） 注意：默认是第一行是导入模版的说明
                    int _mergeRowCount = _remarkRowIndex;//合并行 （必填字段数量） 默认是第一行合并 
                    int _titleRowIndex = 2;//worksheet 行索引（标题）注意：默认是第一行是导入模版的标题
                    int _cellIndex = 1;//worksheet 列索引 注意：默认是第一列开始设置导入模版的标题

                    //模版第一列作为模版使用，所有新增的列样式报错一致
                    var templateCell = worksheet.Cells[_titleRowIndex, _cellIndex];

                    string _remark = string.Empty;  //第一行添加说明，注意换行。

                    //获取要处理的代码生成配置的是增改的模版字段
                    var showCodeGenConfigs = tableFieldList.Where(w => w.WhetherAddUpdate.Equals("Y")).ToList();
                    showCodeGenConfigs = showCodeGenConfigs.Where(x => x.ColumnKey.ToLower() == "false").ToList();
                    int _mergeCellsCount = showCodeGenConfigs.Count();//合并列（模版赋值的标题列数）
                                                                      //获取必填字段

                    //创建模版说明
                    StringBuilder _remarkContentBuilder = GetParseTemplateHint(showCodeGenConfigs);
                    string _remarkContent = _remarkContentBuilder.ToString();

                    #region 合并单元格
                    //合并单元格，合并行和列。默认是合并第一行的所有标题列
                    var cellRange = worksheet.Cells[1, 1, _mergeRowCount, _mergeCellsCount];

                    cellRange.Value = _remarkContent;//合并单元格后的内容赋值
                    var mergeCell = cellRange.Merge = true;//合并
                    int rowHeight = GetRowHeightBasedOnContent(showCodeGenConfigs.Count()); // 根据内容计算行高（这里需要你自己实现逻辑）
                    worksheet.Row(_remarkRowIndex).Height = rowHeight; // 设置行高，注意EPPlus的单位不同，需要转换

                    #endregion

                    //循环创建模版标题列
                    foreach (var item in showCodeGenConfigs)
                    {
                        var currentCell = worksheet.Cells[_titleRowIndex, _cellIndex];
                        //给新模版列标题赋值
                        currentCell.Value = item.ColumnComment;
                        //复制拷贝的excel模版列，给新模版列样式赋值
                        currentCell.StyleID = templateCell.StyleID;
                        // worksheet.Column(_cellIndex).AutoFit();//宽度自适应

                        _cellIndex++;
                    }


                    package.Save();//保存
                }
            }
            catch (Exception ex)
            {
                throw Oops.Oh($"生成导入模版文件异常，请查看系统日志");
            }
            finally { }
        }






        // 这里是一个假设的方法，用于根据单元格内容计算行高。你需要根据实际情况来实现这个逻辑。
        private static int GetRowHeightBasedOnContent(int lineCount)
        {
            // 这里只是一个示例逻辑，你可能需要更复杂的算法来决定合适的行高。

            return (lineCount + 3) * 20; // 
        }


        private StringBuilder GetParseTemplateHint(List<CodeGenConfig> requiredTableFieldList)
        {
            StringBuilder _remarkContentBuilder = new StringBuilder();
            _remarkContentBuilder.AppendLine("");
            _remarkContentBuilder.AppendLine("1.支持Excel2007及以上版本文件。");
            _remarkContentBuilder.AppendLine("2.导入数据时不能超过5000行。");
            _remarkContentBuilder.AppendLine("");
            _remarkContentBuilder.AppendLine("");

            Dictionary<string, string> typeNameDict = new()
            {
                { "string", "输入文本。"},
                { "int", "输入数字。"},
                { "long", "输入数字。"},
                { "decimal", "输入小数。"},
                { "bool", "是,否。"},

            };
            Dictionary<string, string> effectTypeDict = new()
            {
                { "datepicker", "日期。 示例: 2023/3/1。"},
                { "datetimepicker", "日期时间。示例: 2023/3/1 12:00:00。"},

            };

            requiredTableFieldList.ForEach(x =>
            {
                string text = "";
                text += x.ColumnComment + "(" + (x.WhetherRequired.Equals("Y") ? "必填" : "非必填") + "): ";
                if (effectTypeDict.ContainsKey(x.EffectType))
                {
                    text += effectTypeDict[x.EffectType];
                }
                else if (typeNameDict.ContainsKey(x.DtoNetType))
                {
                    text += typeNameDict[x.DtoNetType];
                }
                else if (x.EffectType == "select")
                {
                    var queryValue = x.DtoNetType.Split('.').Last();
                    var enumStr = _sysEnumDataService.GetEnumDataListStr(new EnumDataInput() { EnumName = queryValue });
                    text += enumStr + "。";
                }
                else
                {
                    text += ("注意：类型未能识别出来，需要自己维护！！！。");
                }
                _remarkContentBuilder.AppendLine(text);
            });

            return _remarkContentBuilder;

        }



        /// <summary>
        /// 根据属性名称判断是否是枚举类型
        /// </summary>
        /// <param name="type"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public static bool IsEnumProperty(Type type, string propertyName)
        {
            PropertyInfo propertyInfo = type.GetProperty(propertyName);
            if (propertyInfo == null)
            {
                throw new ArgumentException("Property not found", nameof(propertyName));
            }
            return propertyInfo.PropertyType.IsEnum;
        }
    }
}